import axios from 'axios'
// import Qs from 'qs'
import store from '../store'
import {
  getToken
} from '@/utils/auth'
import {
  Message
} from 'view-design';

// 创建axios实例
const service = axios.create({
  baseURL: process.env.BASE_URL, // api 的 base_url
  timeout: 50000, // 请求超时时间
  //转换数据的方法传统表单
  transformRequest: [
    function (data) {
      if (data !== undefined) {
        //data.type 默认-fromdata  2-json
        if (data.type !== 2) {
          let ret = '';
          for (let it in data) {
            ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&';
          }
          return ret;
        } else {
          return JSON.stringify(data.data)
        }
      }
    }
  ],
})


// request拦截器
service.interceptors.request.use(
  config => {
    if (store.getters.token) {
      config.headers['token'] = getToken() // 让每个请求携带自定义token 请根据实际情况自行修改
    }
    return config
  },
  error => {
    // Do something with request error
    console.log(error) // for debug
    Promise.reject(error)
  }
)

// response 拦截器
service.interceptors.response.use(
  response => {
    /**
     * code为非200是抛错 可结合自己业务进行修改
     */
    const res = response.data
    if (res.status !== 200) {
      if (res.status === 806) {
        location.reload()
      } else if (res.status === 801 || res.status === 802 || res.status === 803 || res.status === 804 || res.status === 804 || res.status === 805 || res.status === 807 || res.status === 808) {
        Message.error(res.msg)
      }
      return Promise.reject(res.msg)
    } else {
      return response.data
    }
  },
  error => {
    Message.error(error.msg)
    console.log('err' + error) // for debug
    return Promise.reject(error)
  }
)

export default service